﻿namespace BEGDC.CC.Web.UserControls.EV
{
    using System;
    using System.Collections;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using BEGDC.CC.BL.CCFlow.EV;
    using BEGDC.Utility.Castle;
    using BEGDC.CC.BL.Common;
    using BEGDC.CC.Entity;
    using BEGDC.CC.BL.CCFlow.CR;
    using BEGDC.CC.BL.Workflow;
    using BEGDC.CC.BL.Common.Query;

    /// <summary>
    ///		Summary description for CheckApp.
    /// </summary>
    public class CheckApp : BaseEV
    {
        protected System.Web.UI.WebControls.Button ibtnSubmit;
        protected System.Web.UI.WebControls.Button ibtnSave;
        protected System.Web.UI.WebControls.Button ibtnQuery;
        protected System.Web.UI.WebControls.Button ibtnReject;
        protected System.Web.UI.WebControls.Button ibtnAssign;
        protected System.Web.UI.WebControls.Button ibtnCheck;
        protected System.Web.UI.WebControls.Button ibtnReply;
        //protected System.Web.UI.WebControls.CheckBoxList CBL_ASBLeader;
        protected System.Web.UI.WebControls.DataGrid dgASBLeaders;
        //protected System.Web.UI.WebControls.DropDownList dropProposedTimeList;

        protected System.Web.UI.WebControls.TextBox txtProposedDate;
        //protected System.Web.UI.WebControls.TextBox txtProposedTime;
        protected System.Web.UI.WebControls.TextBox txtOptionalDate;
        //protected System.Web.UI.WebControls.TextBox txtOptionalTime;
        protected System.Web.UI.WebControls.TextBox txtCompany;
        protected System.Web.UI.WebControls.TextBox txtVenue;
        protected System.Web.UI.WebControls.TextBox txtVisitingPurpose;
        protected System.Web.UI.WebControls.CheckBoxList chkListActivities;
        protected System.Web.UI.WebControls.TextBox tbOperationFlag;
        protected System.Web.UI.WebControls.TextBox tbOperationContent;
        protected System.Web.UI.WebControls.Label lblDept;
        protected System.Web.UI.WebControls.Label lblDeptValue;
        //protected System.Web.UI.WebControls.Label lblApplicantValue;
        protected System.Web.UI.WebControls.Label lblAccount;
        protected System.Web.UI.WebControls.DataGrid dtGridProExecutives;
        protected System.Web.UI.WebControls.Button Img1;
        protected System.Web.UI.HtmlControls.HtmlInputHidden txtEmployeeID;
        protected System.Web.UI.HtmlControls.HtmlInputHidden txtComments;
        protected System.Web.UI.WebControls.TextBox tbComment;
        protected System.Web.UI.WebControls.DataGrid dgCustomerList;
        protected System.Web.UI.WebControls.Button CustomerPaneImg;
        protected System.Web.UI.WebControls.Label lblCATBranchValue;
        protected System.Web.UI.WebControls.TextBox lblCluster;
        protected System.Web.UI.WebControls.Label lblAccountValue;
        protected System.Web.UI.WebControls.Label lblProDateValue;
        //protected System.Web.UI.WebControls.Label lblProTimeValue;
        protected System.Web.UI.WebControls.Label lblOptDateValue;
        //protected System.Web.UI.WebControls.Label lblOptTimeValue;
        protected System.Web.UI.WebControls.Label lblCompanyValue;
        protected System.Web.UI.WebControls.Label lblVenueValue;
        protected System.Web.UI.WebControls.Label lblActivityValue;
        //protected System.Web.UI.HtmlControls.HtmlGenericControl ProposedDate;
        //protected System.Web.UI.HtmlControls.HtmlGenericControl OptionalDate;
        protected System.Web.UI.WebControls.Label Lb_CISWarning;
        protected System.Web.UI.WebControls.Label lblLegalEntity;
        protected System.Web.UI.HtmlControls.HtmlTableCell tdVisitingPur;
        protected BEGDC.CC.Web.Common.StampCtrl stampCtrl1;
        protected System.Web.UI.WebControls.Label lbAppNo;
        protected ASB.CC.Web.UserControls.RequesterInfoControl RequesterInfoControl;
        protected System.Web.UI.HtmlControls.HtmlInputHidden positionflag;
        #region Property
        protected string Step
        {
            get
            {
                IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = queryService.QueryFlowInstance(this.AppID);
                if (flowInstance == null)
                    return "Close";
                else
                    return flowInstance.CurrentStep.StepCode;
            }
        }

        protected string ActiveStep
        {
            get
            {
                IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = queryService.QueryFlowInstance(this.AppID);
                if (flowInstance == null)
                    return "Close";
                else
                    return flowInstance.CurrentActiveStep.StepCode;
            }
        }

        private int CustInfoID
        {
            get
            {
                if (ViewState["CustInfoID"] == null)
                    return 0;
                else
                    return Convert.ToInt32(ViewState["CustInfoID"]);
            }
            set
            {
                ViewState["CustInfoID"] = value;
            }
        }
        private CustomerInfo CustInfo
        {
            get
            {
                if (Session[CustInfoID + "CustInfo"] == null)
                    return null;
                else
                    return (CustomerInfo)Session[CustInfoID + "CustInfo"];
            }
            set
            {
                Session[CustInfoID + "CustInfo"] = value;
            }
        }

        private object AlAttendee
        {
            get
            {
                return Session[SessionFlag.AccompanySessionEZ];
            }
            set
            {
                Session[SessionFlag.AccompanySessionEZ] = value;
            }
        }

        private bool IsView
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                if (state == SysDicItem.ProjectStatusFlag.View || state == SysDicItem.ProjectStatusFlag.CANCEL
                    || state == SysDicItem.ProjectStatusFlag.Pending || state == SysDicItem.ProjectStatusFlag.End
                    || state == SysDicItem.ProjectStatusFlag.Participation)
                    return true;
                else
                    return false;
            }
        }

        private bool IsQuery
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                return state == SysDicItem.ProjectStatusFlag.QUERY;
            }
        }


        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
            if (!Page.IsPostBack)
            {
                base.InitCommonData();

                this.RequesterInfoControl.isReadOnly = ((EVAccessControl)Access).IsReadOnlyForApp;

                InitAppInfo();
                InitAccountInfo();

                this.AlAttendee = null;
                Session[SessionFlag.CustomerSessionEZ] = null;

                //Set controls condition
                ControlStatusSetting();

                this.ibtnReply.Attributes.Add("onclick", "javascript:OpenReplyPane(" + Request.QueryString["flowid"] + ")");
                this.ibtnAssign.Attributes["onclick"] = "javascript:AssignApp();";
                this.ibtnSubmit.Attributes["onclick"] = "javascript:OnSubmit();";
                //this.ibtnSave.Attributes["onclick"] = "javascript:OnSave();";
                this.ibtnReject.Attributes["onclick"] = "javascript:OnReject();";
                this.ibtnCheck.Attributes["onclick"] = "javascript:OnCheck();";
                this.ibtnQuery.Attributes.Add("onclick", "javascript:OpenQueryPane(" + Request.QueryString["flowid"] + ")");

                this.Img1.Attributes["onclick"] = "javascript:OpenALAttendeePane(0);";
                this.CustomerPaneImg.Attributes["onclick"] = "javascript:OpenCustomerPane(0);";
            }
            BindCustomerAttendee();
            this.BindALAttendee();
            this.BindASBLeaders();
            //Show textbox or label
            if (this.Access != null)
                ControlVisibleSetting(((EVAccessControl)Access).IsReadOnlyForApp);
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ibtnReply.Click += new EventHandler(ibtnReply_Click);
            this.ibtnSubmit.Click += new EventHandler(ibtnSubmit_Click);
            this.ibtnAssign.Click += new EventHandler(ibtnAssign_Click);
            this.ibtnCheck.Click += new EventHandler(ibtnCheck_Click);
            this.ibtnReject.Click += new EventHandler(ibtnReject_Click);
            this.ibtnQuery.Click += new EventHandler(ibtnQuery_Click);
            this.ibtnSave.Click += new EventHandler(ibtnSave_Click);
            this.dgCustomerList.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgCustomerList_ItemCommand);
            this.dgCustomerList.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgCustomerList_ItemDataBound);
            this.dtGridProExecutives.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dtGridProExecutives_ItemCommand);
            this.dtGridProExecutives.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dtGridProExecutives_ItemDataBound);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        /// <summary>
        /// isQuery==true, show lables, or show textboxes;
        /// </summary>
        /// <param name="isQuery"></param>
        private void ControlVisibleSetting(bool isReadonly)
        {
            if (isReadonly)
            {

                #region Set TextBox invisible
                this.txtCompany.Visible = false;
                this.txtOptionalDate.Visible = false;
                //this.txtOptionalTime.Visible = false;
                this.txtProposedDate.Visible = false;
                //this.txtProposedTime.Visible = false;
                this.txtVenue.Visible = false;
                this.txtVisitingPurpose.Visible = false;
                this.chkListActivities.Visible = false;
                //this.dropProposedTimeList.Visible = false;
                //this.OptionalDate.Visible = false;
                // this.ProposedDate.Visible = false;
                #endregion

                #region Set Application Infomation
                if (this.Application != null)
                {
                    //this.lblApplicantValue.Text = Application.RequesterNameEN;
                    this.lblAccountValue.Text = Application.Account;
                    this.lblDeptValue.Text = Application.RequesterDept;
                    if (this.Application.DepartmentName != null)
                    {
                        //this.lblCATBranchValue.Text = Application.DepartmentName.DepartmentCode;
                        this.lblCATBranchValue.Text = Application.CATBranch;
                        this.lblCluster.Text = Application.Others;
                        //this.lblCluster.CssClass = "Cluster_Block";
                    }

                    if (Application.RequestedDateFrom != Nullables.NullableDateTime.Default)
                    {
                        this.lblProDateValue.Text = WebUtility.FormatDateString(Application.RequestedDateFrom.Value);
                        //this.lblProTimeValue.Text = Application.RequestedDateFrom.Value.ToString("HH:mm");

                    }
                    if (Application.AlternateDateFrom != Nullables.NullableDateTime.Default)
                    {
                        this.lblOptDateValue.Text = WebUtility.FormatDateString(Application.AlternateDateFrom.Value);
                        //this.lblOptTimeValue.Text = Application.AlternateDateFrom.Value.ToString("HH:mm");
                    }
                    this.lblActivityValue.Text = Application.Activity;
                }

                BEGDC.CC.BL.Common.Query.IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;
                CustomerInfo custInfo = queryService.GetCustomerInfo(this.AppID);
                if (custInfo != null)
                {
                    this.CustInfoID = custInfo.Id;
                    this.CustInfo = custInfo;
                }
                if (this.CustInfo != null)
                {
                    this.lblCompanyValue.Text = CustInfo.Company;
                    this.lblVenueValue.Text = CustInfo.Venue;
                    if (CustInfo.VisitObjective + string.Empty != string.Empty)
                        this.tdVisitingPur.InnerHtml = CustInfo.VisitObjective.Replace("\r\n", "<br>");
                }
                #endregion

                //Hide add button
                this.Img1.Visible = false;
                this.CustomerPaneImg.Visible = false;

                //Hide Action Column
                this.dgCustomerList.Columns[6].Visible = false;
                this.dtGridProExecutives.Columns[3].Visible = false;
            }
            else
            {
                this.lblActivityValue.Visible = false;
                this.lblActivityValue.Visible = false;
                this.lblCompanyValue.Visible = false;
                this.lblOptDateValue.Visible = false;
                //this.lblOptTimeValue.Visible = false;
                this.lblProDateValue.Visible = false;
                //this.lblProTimeValue.Visible = false;
                this.lblVenueValue.Visible = false;

                //Set Application Infomation
                InitAccountInfo();
                InitAppInfo();
            }


        }

        protected override void ButtonStatusSetting()
        {
            if (Access != null)
            {
                if (Access.IsHideAllButton)
                {
                    this.ibtnSave.Visible = false;
                    this.ibtnAssign.Visible = false;
                    this.ibtnSubmit.Visible = false;
                    this.ibtnReject.Visible = false;
                    this.ibtnCheck.Visible = false;
                    this.ibtnQuery.Visible = false;
                    this.ibtnReply.Visible = false;

                    this.dgCustomerList.Columns[6].Visible = false;
                    this.dtGridProExecutives.Columns[3].Visible = false;

                }
                else if (Access.IsQuery)
                {
                    this.ibtnSave.Visible = true;
                    this.ibtnAssign.Visible = false;
                    this.ibtnSubmit.Visible = false;
                    this.ibtnReject.Visible = false;
                    this.ibtnCheck.Visible = false;
                    this.ibtnQuery.Visible = false;
                    this.ibtnReply.Visible = true;

                    //					this.Img1.Visible = false;
                    //					this.dgCustomerList.Columns[6].Visible = false;
                    //					this.dtGridProExecutives.Columns[3].Visible = false;
                }
                else
                {
                    this.ibtnAssign.Visible = Access.IsButtonVisible(EVTransitionList.Assign);
                    this.ibtnSubmit.Visible = Access.IsButtonVisible(EVTransitionList.Submit);
                    this.ibtnReject.Visible = Access.IsButtonVisible(EVTransitionList.Reject);
                    this.ibtnCheck.Visible = Access.IsButtonVisible(EVTransitionList.Check);
                    this.ibtnQuery.Visible = Access.IsButtonVisible(EVTransitionList.Query);
                    this.ibtnReply.Visible = false;
                }

            }
        }

        protected override void ControlStatusSetting()
        {
            ButtonStatusSetting();
        }




        private void InitAccountInfo()
        {
            if (Application == null)
            {
                return;
            }
            else
            {
                if (Application.RequesterNo != null)
                {
                    //this.lblApplicantValue.Text = Application.RequesterNo.NameEN;
                    this.lblDeptValue.Text = Application.RequesterDept;
                    if (Application.DepartmentName != null)
                    {
                        //this.lblCATBranchValue.Text = Application.DepartmentName.DepartmentCode;
                        this.lblCATBranchValue.Text = Application.CATBranch;
                        this.lblCluster.Text = Application.Others;
                        //this.lblCluster.CssClass = "Cluster_Block";
                    }
                    this.lblAccountValue.Text = Application.Account;
                    if (Application.DepartmentType.DicItemKey == "CAT")
                    {
                        this.lblAccount.Visible = false;
                        this.lblAccountValue.Visible = false;
                    }
                }
            }
        }

        private void InitAppInfo()
        {
            try
            {
                if (this.Application != null && this.Application.AppNo != string.Empty)
                    this.lbAppNo.Text = " Application No:" + this.Application.AppNo;

                BEGDC.CC.BL.Common.Query.IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;

                this.chkListActivities.DataSource = queryService.GetDicItemByTypeName(BEGDC.CC.BL.Common.DicType.ACTIVITY);
                this.chkListActivities.DataTextField = "DicItemKey";
                this.chkListActivities.DataBind();



                CustomerInfo custInfo = queryService.GetCustomerInfo(this.AppID);
                if (custInfo != null)
                {
                    this.CustInfoID = custInfo.Id;
                    this.CustInfo = custInfo;
                }

                SetInitInfo();
            }
            catch (BEGDC.Utility.ExceptionManagement.GDCException gdcEx)
            {
                //todo
            }
        }

        private void SetInitInfo()
        {
            //#region Proposed Time
            ////init Proposed Time Value
            //if (dropProposedTimeList.Items.Count < 1)
            //{
            //    for (int proposedTimeStar = 9; proposedTimeStar < 21; proposedTimeStar++)
            //    {
            //        this.dropProposedTimeList.Items.Add(new ListItem(proposedTimeStar.ToString("00") + ":00"));
            //        this.dropProposedTimeList.Items.Add(new ListItem(proposedTimeStar.ToString("00") + ":30"));
            //    }
            //    this.dropProposedTimeList.Items.Insert(0, new ListItem("Please Select", String.Empty));
            //}
            //#endregion

            #region Init Application Information
            if (this.Application != null)
            {
                if (Application.RequestedDateFrom != Nullables.NullableDateTime.Default)
                {
                    //string nullProposedDateStr = WebUtility.FormatDateString(new DateTime(1990, 1, 1));
                    //this.txtProposedDate.Text = WebUtility.FormatDateString(Application.RequestedDateFrom.Value) == nullProposedDateStr ? "" : WebUtility.FormatDateString(Application.RequestedDateFrom.Value);
                    ////this.txtProposedTime.Text = Application.RequestedDateFrom.Value.ToString("HH:mm");
                    //var item = this.dropProposedTimeList.Items.FindByText(Application.RequestedDateFrom.Value.ToString("HH:mm"));
                    //if (item != null) item.Selected = true;
                    this.txtProposedDate.Text = WebUtility.FormatDateString(Application.RequestedDateFrom.Value);
                }
                if (Application.AlternateDateFrom != Nullables.NullableDateTime.Default)
                {
                    this.txtOptionalDate.Text = WebUtility.FormatDateString(Application.AlternateDateFrom.Value);
                    //if (Application.AlternateDateFrom.Value.Hour != 0 || Application.AlternateDateFrom.Value.Minute != 0)
                    //this.txtOptionalTime.Text = Application.AlternateDateFrom.Value.ToString("HH:mm");
                }

                //if (Application.DepartmentName != null)
                //    this.lblCATBranchValue.Text = Application.DepartmentName.DepartmentCode;
                this.lblCATBranchValue.Text = Application.CATBranch;
                this.lblCluster.Text = Application.Others;
                //this.lblCluster.CssClass = "Cluster_Block";
                this.lblAccountValue.Text = Application.Account;
                if (Application.DepartmentType.DicItemKey == "CAT")
                {
                    this.lblAccountValue.Visible = false;
                    this.lblAccount.Visible = false;
                }
                if (Application.LegalEntity != null)
                {
                    this.lblLegalEntity.Text = Application.LegalEntity.LegalEntityName;
                }

                this.SelectActivites(Application.Activity);
            }
            #endregion

            //Set Customer information
            if (this.CustInfo != null)
            {
                this.txtCompany.Text = CustInfo.Company;
                this.txtVenue.Text = CustInfo.Venue;
                this.txtVisitingPurpose.Text = CustInfo.VisitObjective;
            }
        }

        private void SelectActivites(string activies)
        {
            if (activies + string.Empty == string.Empty)
            {
                return;
            }
            string[] activity = activies.Split(';');
            for (int i = 0; i < activity.Length; i++)
            {
                foreach (ListItem li in this.chkListActivities.Items)
                {
                    if (li.Text == activity[i])
                    {
                        li.Selected = true;
                        break;
                    }
                }
            }
        }

        private string BuildSelectedActivies()
        {
            string activies = string.Empty;
            foreach (ListItem li in this.chkListActivities.Items)
            {
                if (li.Selected)
                {
                    activies += li.Text + ";";
                }
            }
            return activies.Trim(';');
        }

        private void BindCustomerAttendee()
        {
            DataTable CustomerDataTable = null;
            object SessCustomerAttendee = Session[SessionFlag.CustomerSessionEZ];
            if (SessCustomerAttendee != null)
            {
                CustomerDataTable = (DataTable)SessCustomerAttendee;
            }
            else
            {
                if (this.CustInfoID > 0)
                {
                    IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
                    CustomerDataTable = queryService.GetCustomerAttendeeList(this.CustInfoID);
                }
                if (CustomerDataTable != null && CustomerDataTable.Rows.Count > 0)
                {
                    Session[SessionFlag.CustomerSessionEZ] = CustomerDataTable;
                }
                else
                {
                    CustomerDataTable = new DataTable();
                    CustomerDataTable.Columns.Add(new DataColumn("Id", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Name", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("NameCN", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("CompanyEN", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Company", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Title", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("TitleEN", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Responsibility", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Affects", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("ResponsibilityID", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("AffectsID", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("Remark", typeof(System.String)));
                    CustomerDataTable.Columns.Add(new DataColumn("IsExisted", typeof(System.String)));
                    Session[SessionFlag.CustomerSessionEZ] = CustomerDataTable;
                }
            }
            if (CustomerDataTable.Select("IsExisted='" + BEGDC.CC.BL.Common.CISFlag.NotExisted + "'").Length > 0)
            {
                this.Lb_CISWarning.Visible = true;
            }
            else
            {
                this.Lb_CISWarning.Visible = false;
            }
            this.dgCustomerList.DataSource = this.SetRowID(CustomerDataTable);
            this.dgCustomerList.DataBind();
        }

        private DataTable SetRowID(DataTable table)
        {
            if (table != null && table.Rows.Count > 0)
                for (int i = 1; i <= table.Rows.Count; i++)
                {
                    table.Rows[i - 1][0] = i.ToString();
                }
            return table;
        }


        private void BindALAttendee()
        {
            DataTable AccompanyingAttendee = null;
            if (AlAttendee != null)
            {
                AccompanyingAttendee = (DataTable)AlAttendee;
            }
            else
            {
                if (this.AppID > 0)
                {
                    ICR crService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                    AccompanyingAttendee = crService.GetAccompanyingAttendeeList(this.AppID);
                }
                if (AccompanyingAttendee == null || AccompanyingAttendee.Rows.Count == 0)
                {
                    AccompanyingAttendee = new DataTable();
                    AccompanyingAttendee.Columns.Add(new DataColumn("Id", typeof(System.String)));
                    AccompanyingAttendee.Columns.Add(new DataColumn("EmployeeId", typeof(System.String)));
                    AccompanyingAttendee.Columns.Add(new DataColumn("Name", typeof(System.String)));
                    AccompanyingAttendee.Columns.Add(new DataColumn("Title", typeof(System.String)));
                }
                AlAttendee = AccompanyingAttendee;
            }
            this.dtGridProExecutives.DataSource = AccompanyingAttendee;
            this.dtGridProExecutives.DataBind();
        }



        private void BuildObj2Save()
        {

            if (base.Application == null)
            {
                Application = new Application();
            }

            Application.ApplyForSomeoneElse = false;
            Application.IsReviewedGuideline = false;
            //Application.RequesterNameEN = HttpContext.Current.User.Identity.Name;  //Remove by John fix applicant change
            Application.Account = this.lblAccountValue.Text;
            Application.RequesterDept = this.lblDeptValue.Text;
            Application.CATBranch = this.lblCATBranchValue.Text;
            Application.RequesterMobile = this.RequesterInfoControl.Mobile;
            Application.RequesterOfficeTel = this.RequesterInfoControl.OfficePhone;

            IQuery query = AppContainer.Instance[ServiceConst.QueryService] as IQuery;

            //Application.DepartmentName = query.GetDepartmentByCode(this.lblCATBranchValue.Text);
            //Application.DepartmentType = Application.DepartmentName.DepartmentType;

            if (!string.IsNullOrEmpty(this.lblCluster.Text))
            {
                Application.DepartmentName = query.GetDepartmentByPCAT(this.lblCATBranchValue.Text, true);
                //this.lblCluster.CssClass = "Cluster_Block";
            }
            else
            {
                Application.DepartmentName = query.GetDepartmentByPCAT(this.lblCATBranchValue.Text, false);
            }

            Application.ApplicationType = BEGDC.CC.BL.Workflow.WorkflowTypes.EV;
            if (this.txtProposedDate.Text != string.Empty)
            {
                //string requestedDate = this.txtProposedDate.Text + " " + this.dropProposedTimeList.SelectedValue;
                ////if (this.txtProposedTime.Text != string.Empty)
                ////    requestedDate += " " + this.txtProposedTime.Text;
                //Application.RequestedDateFrom = new Nullables.NullableDateTime(Convert.ToDateTime(requestedDate));
                //Application.RequestedDateTo = Application.RequestedDateTo;
                Application.RequestedDateFrom = new Nullables.NullableDateTime(Convert.ToDateTime(this.txtProposedDate.Text));
                Application.RequestedDateTo = Application.RequestedDateTo;
            }
            else
            {
                Application.RequestedDateFrom = Nullables.NullableDateTime.Default;
                Application.RequestedDateTo = Application.RequestedDateFrom;
                //if (!string.IsNullOrEmpty(this.dropProposedTimeList.SelectedValue))
                //{
                //    string nullProposedDateStr = WebUtility.FormatDateString(new DateTime(1990, 1, 1));
                //    string requestedDate = nullProposedDateStr + " " + this.dropProposedTimeList.SelectedValue;
                //    Application.RequestedDateFrom = new Nullables.NullableDateTime(Convert.ToDateTime(requestedDate));
                //    //Application.RequestedDateTo = Application.RequestedDateFrom;
                //}
                //else
                //{
                //    Application.RequestedDateFrom = Nullables.NullableDateTime.Default;
                //    Application.RequestedDateTo = Application.RequestedDateFrom;
                //}
            }

            if (this.txtOptionalDate.Text != string.Empty)
            {
                string optionalDate = this.txtOptionalDate.Text;
                //if (this.txtOptionalTime.Text != string.Empty)
                //    optionalDate += " " + this.txtOptionalTime.Text;
                Application.AlternateDateFrom = new Nullables.NullableDateTime(Convert.ToDateTime(optionalDate));

            }
            Application.Activity = BuildSelectedActivies();

            //build CustomerInfo object
            if (this.CustInfo == null)
            {
                CustInfo = new CustomerInfo();
            }
            CustInfo.Application = this.Application;
            CustInfo.Company = txtCompany.Text;
            CustInfo.Venue = txtVenue.Text;
            CustInfo.VisitObjective = txtVisitingPurpose.Text;
        }

        private void BuildALAttendee(ref System.Collections.IList attendeeList)
        {
            // AL Attendee Info
            if (this.AlAttendee == null)
                return;

            DataTable table = (DataTable)this.AlAttendee;
            if (table != null && table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    ALAttendee al = new ALAttendee();
                    al.Id = Convert.ToInt32(table.Rows[i]["Id"].ToString());
                    al.EmployeeId = new Employee();
                    al.EmployeeId.Id = table.Rows[i]["EmployeeId"].ToString();
                    al.Title = table.Rows[i]["Title"].ToString();
                    attendeeList.Add(al);
                }
            }
        }

        private void BuildCustomerAttendee(ref IList custAttendeeList)
        {
            DataTable table = (DataTable)this.dgCustomerList.DataSource;
            if (table != null && table.Rows.Count > 0)
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    CustomerAttendee cus = new CustomerAttendee();
                    cus.NameEN = table.Rows[i]["Name"].ToString();
                    cus.Title = table.Rows[i]["Title"].ToString();
                    cus.Company = table.Rows[i]["Company"].ToString();
                    cus.NameCN = table.Rows[i]["NameCN"].ToString();
                    cus.TitleEN = table.Rows[i]["TitleEN"].ToString();
                    cus.CompanyEN = table.Rows[i]["CompanyEN"].ToString();

                    cus.Responsibility = new DicItem();
                    cus.Responsibility.Id = Convert.ToInt32(table.Rows[i]["ResponsibilityID"]);
                    cus.Affects = new DicItem();
                    cus.Affects.Id = Convert.ToInt32(table.Rows[i]["AffectsID"]);
                    cus.IsAttended = true;
                    cus.IsExisted = Convert.ToInt32(table.Rows[i]["IsExisted"]);
                    cus.Remark = table.Rows[i]["Remark"].ToString();

                    custAttendeeList.Add(cus);
                }
            }
        }



        #region DataGrid events
        private void dtGridProExecutives_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                ImageButton Btn_Edit = (ImageButton)e.Item.Cells[3].FindControl("Btn_ALEdit");
                string ItemId = e.Item.Cells[0].Text.ToString();
                Btn_Edit.Attributes.Add("onclick", "OpenALAttendeePane('" + ItemId + "');");

                ImageButton btnDel = (ImageButton)e.Item.Cells[3].FindControl("Btn_ALDelete");
                btnDel.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?')");
            }
        }

        private void dtGridProExecutives_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                string itemId = e.Item.Cells[0].Text;
                if (this.AlAttendee != null)
                {
                    DataTable table = (DataTable)this.AlAttendee;
                    DataRow[] rows = table.Select("Id =" + itemId);
                    table.Rows.Remove(rows[0]);
                    this.dtGridProExecutives.DataSource = table;
                    this.dtGridProExecutives.DataBind();
                    this.AlAttendee = table;
                }
            }
        }

        #endregion


        void ibtnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                IList attTypes = new ArrayList();
                attTypes.Add(BEGDC.CC.BL.CCFlow.AttachmentType.SUMMARY);
                attTypes.Add(BEGDC.CC.BL.CCFlow.AttachmentType.AGENDA);
                string msg = BEGDC.CC.BL.CCFlow.AttachmentService.GetMissedAttachmentMessage(this.AppID, attTypes);
                if (msg + string.Empty != string.Empty)
                {
                    Page.RegisterClientScriptBlock("", "<script>alert('" + msg + "')</script>");
                    return;
                }


                IEV evService = AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.EVService] as IEV;
                this.BuildObj2Save();
                IList list = new ArrayList();
                this.BuildALAttendee(ref list);

                IList custAttendeeList = new ArrayList();
                BuildCustomerAttendee(ref custAttendeeList);
                evService.SubmitCheckApp(this.Application, this.CustInfo, list, custAttendeeList, null);

                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');window.close();</script>");

            }
            catch (BEGDC.Utility.ExceptionManagement.GDCException gdcEx)
            {
                string message = gdcEx.Message;
                Response.Write("<script>alert('+message+')</script>");
            }
        }

        void ibtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.BuildObj2Save();
                IList list = new ArrayList();

                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                this.BuildALAttendee(ref list);
                IList custAttendeeList = new ArrayList();
                BuildCustomerAttendee(ref custAttendeeList);
                evService.SaveEVRequest(this.Application, this.CustInfo, list, custAttendeeList, null);

                string url = string.Empty + Request.Form["tbURL"];
                string script = "<script>";
                //				if(url == string.Empty)
                //					script += "VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');";
                if (url != string.Empty)
                {
                    script += "window.location.href='" + url + "'";
                }
                script += "</script>";

                Page.RegisterClientScriptBlock("", script);

            }
            catch
            {
            }

        }

        void ibtnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.tbOperationFlag.Text == "query")
                {
                    IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                    string comment = string.Empty;
                    if (Session["Comment"] != null)
                        comment = Session["Comment"].ToString();
                    evService.Query(Convert.ToInt64(Request.QueryString["flowid"]), this.tbOperationContent.Text, comment);
                    Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');window.close();</script>");
                }
            }
            catch
            {
            }
        }

        private void ibtnDrawback_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                evService.Drawback(this.Application, null);
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');window.close();</script>");
            }
            catch
            {
            }
        }

        void ibtnReject_Click(object sender, EventArgs e)
        {
            try
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                evService.RejectCheckApp(this.Application, WebUtility.DeCodeString(this.Server, this.tbComment.Text));
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');window.close();</script>");

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        void ibtnAssign_Click(object sender, EventArgs e)
        {
            try
            {

                this.BuildObj2Save();
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;

                string EmployeeID = this.txtEmployeeID.Value;
                BEGDC.CC.BL.UserManagement.IUser userService = AppContainer.Instance[ServiceConst.UserService] as BEGDC.CC.BL.UserManagement.IUser;
                Employee employee = userService.GetUserByID(EmployeeID);

                IList list = new ArrayList();
                this.BuildALAttendee(ref list);
                IList custAttendeeList = new ArrayList();
                BuildCustomerAttendee(ref custAttendeeList);

                evService.AssignEVRequest(this.Application, employee, this.CustInfo, list, custAttendeeList);

                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');window.close();</script>");


            }
            catch
            {
            }
        }

        void ibtnCheck_Click(object sender, EventArgs e)
        {
            try
            {
                IList attTypes = new ArrayList();
                attTypes.Add(BEGDC.CC.BL.CCFlow.AttachmentType.SUMMARY);
                attTypes.Add(BEGDC.CC.BL.CCFlow.AttachmentType.AGENDA);
                string msg = BEGDC.CC.BL.CCFlow.AttachmentService.GetMissedAttachmentMessage(this.AppID, attTypes);
                if (msg + string.Empty != string.Empty)
                {
                    Page.RegisterClientScriptBlock("", "<script>alert('" + msg + "')</script>");
                    return;
                }

                this.BuildObj2Save();
                IList list = new ArrayList();

                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                this.BuildALAttendee(ref list);

                IList custAttendeeList = new ArrayList();
                BuildCustomerAttendee(ref custAttendeeList);

                evService.SaveEVRequest(this.Application, this.CustInfo, list, custAttendeeList, null);

                BEGDC.CC.BL.UserManagement.IUser userService = AppContainer.Instance[ServiceConst.UserService] as BEGDC.CC.BL.UserManagement.IUser;
                Employee employee = userService.GetUserByEnglishName(HttpContext.Current.User.Identity.Name);

                evService.SubmitAssignCheckApp(this.Application, employee);
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');window.close();</script>");
            }
            catch
            {
            }
        }

        private void dgCustomerList_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                ImageButton Btn_Edit = (ImageButton)e.Item.Cells[8].FindControl("Btn_Edit");
                string ItemId = e.Item.Cells[0].Text.ToString();
                Btn_Edit.Attributes.Add("onclick", "OpenCustomerPane('" + ItemId + "');");
                Btn_Edit.Attributes.Add("check", "false");

                ImageButton ld = (ImageButton)e.Item.Cells[8].FindControl("Btn_Delete");
                if (ld != null)
                {
                    ld.Attributes.Add("onclick", "return confirm('Are you sure to delete this item?');");
                    ld.Attributes.Add("check", "false");
                }

                string IsExisted = e.Item.Cells[6].Text.ToString();
                if (IsExisted == BEGDC.CC.BL.Common.CISFlag.NotExisted)
                {
                    System.Web.UI.WebControls.Image WarningImg = (System.Web.UI.WebControls.Image)e.Item.Cells[7].FindControl("CISWarning");
                    WarningImg.Visible = true;
                    WarningImg.ImageUrl = "../../images/Warning.gif";
                    WarningImg.ToolTip = "The Customer is not in CIS (该客户不是CIS成员)";
                }

                if (IsExisted == BEGDC.CC.BL.Common.CISFlag.Existed)
                {
                    System.Web.UI.WebControls.Image WarningImg = (System.Web.UI.WebControls.Image)e.Item.Cells[7].FindControl("CISWarning");
                    WarningImg.ImageUrl = "../../images/GreenWarningImg.gif";
                    WarningImg.ToolTip = "The Customer is in CIS (该客户是CIS成员)";
                    WarningImg.Visible = true;
                }
            }
        }

        private void dgCustomerList_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "Delete")
                {

                    int rowid = Convert.ToInt32(e.Item.Cells[0].Text);

                    DataTable contractInfo = (DataTable)Session[SessionFlag.CustomerSessionEZ];
                    DataRow contractRow = contractInfo.Rows[rowid - 1];
                    contractInfo.Rows.Remove(contractRow);
                    this.BindCustomerAttendee();
                }
            }
            catch
            {
            }
        }


        void ibtnReply_Click(object sender, EventArgs e)
        {
            IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
            if (this.tbOperationFlag.Text == "reply")
            {
                this.BuildObj2Save();
                IList list = new ArrayList();

                evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                this.BuildALAttendee(ref list);
                IList custAttendeeList = new ArrayList();
                BuildCustomerAttendee(ref custAttendeeList);
                evService.SaveEVRequest(this.Application, this.CustInfo, list, custAttendeeList, null);

                evService.ReplyQuery(Convert.ToInt64(Request.QueryString["flowid"]), WebUtility.DeCodeString(Server, this.tbOperationContent.Text));
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');window.close();</script>");
            }
        }
        private void BindASBLeaders()
        {
            //this.CBL_ASBLeader.Enabled = false;
            BEGDC.CC.BL.Common.Query.IQuery query = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;
            //DataTable table = query.GetAppASBLeadersList(this.Application.Id);
            //this.CBL_ASBLeader.DataSource = table.DefaultView;
            //this.CBL_ASBLeader.DataValueField = "DicItemID";
            //this.CBL_ASBLeader.DataTextField = "DicItemKey";
            //this.CBL_ASBLeader.DataBind();

            DataTable table2 = query.GetAppASBLeadersList2(this.Application.Id);
            this.dgASBLeaders.DataSource = table2;
            this.dgASBLeaders.DataBind();
        }
    }
}
